<template>
  <div class="learning-manage-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-container">
        <div class="navbar-left">
          <router-link to="/" class="logo-link">
            <svg viewBox="0 0 24 24" width="32" height="32" fill="currentColor">
              <path d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z"/>
            </svg>
            <span class="logo">M-Learning</span>
          </router-link>
        </div>
        
        <div class="navbar-center">
          <router-link to="/" class="nav-link">首页</router-link>
          <router-link to="/learning" class="nav-link">在线学习</router-link>
          <router-link to="/problems" class="nav-link">在线答题</router-link>
          <router-link to="/discussion" class="nav-link">学习社区</router-link>
          <router-link to="/profile" class="nav-link">个人中心</router-link>
        </div>
        
        <div class="navbar-right">
          <div class="user-info">
            <img :src="getAvatarUrl(userInfo.avatar)" class="user-avatar" alt="头像" />
            <span class="username">{{ userInfo.username }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <div class="content-container">
        <!-- 页面标题 -->
        <div class="page-header">
          <div>
            <h1>📹 课程管理</h1>
            <p class="subtitle">管理所有课程、章节和视频</p>
          </div>
          <div class="header-actions">
            <button @click="showCreateCourse = true" class="btn-primary">
              ➕ 创建课程
            </button>
            <button @click="showCreateCategory = true" class="btn-secondary">
              📁 创建分类
            </button>
          </div>
        </div>

        <!-- 筛选栏 -->
        <div class="filter-bar">
          <div class="filter-left">
            <select v-model="filterCategory" class="filter-select">
              <option :value="null">全部分类</option>
              <option v-for="cat in categories" :key="cat.id" :value="cat.id">
                {{ cat.icon }} {{ cat.name }}
              </option>
            </select>
            
            <select v-model="filterStatus" class="filter-select">
              <option value="">全部状态</option>
              <option value="draft">草稿</option>
              <option value="published">已发布</option>
            </select>
          </div>
          
          <div class="filter-right">
            <input 
              v-model="searchKeyword" 
              type="text" 
              placeholder="搜索课程..." 
              class="search-input"
            />
          </div>
        </div>

        <!-- 课程列表 -->
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>

        <div v-else-if="filteredCourses.length === 0" class="empty-state">
          <p>暂无课程</p>
          <button @click="showCreateCourse = true" class="btn-primary">创建第一个课程</button>
        </div>

        <div v-else class="course-table">
          <table>
            <thead>
              <tr>
                <th style="width: 80px">封面</th>
                <th>课程名称</th>
                <th style="width: 120px">分类</th>
                <th style="width: 100px">难度</th>
                <th style="width: 80px">视频数</th>
                <th style="width: 80px">学习人数</th>
                <th style="width: 100px">状态</th>
                <th style="width: 200px">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="course in filteredCourses" :key="course.id">
                <td>
                  <img :src="course.cover || 'https://via.placeholder.com/80x45'" class="course-thumb" />
                </td>
                <td>
                  <div class="course-title">{{ course.title }}</div>
                  <div class="course-desc">{{ course.description }}</div>
                </td>
                <td>
                  <span class="category-badge">
                    {{ getCategoryName(course.categoryId) }}
                  </span>
                </td>
                <td>
                  <span :class="['difficulty-badge', course.difficulty]">
                    {{ getDifficultyLabel(course.difficulty) }}
                  </span>
                </td>
                <td>{{ course.videoCount || 0 }}</td>
                <td>{{ course.studentCount || 0 }}</td>
                <td>
                  <span :class="['status-badge', course.status]">
                    {{ getStatusLabel(course.status) }}
                  </span>
                </td>
                <td>
                  <div class="action-buttons">
                    <button @click="manageChapters(course)" class="btn-small btn-manage" title="管理章节">
                      📚 章节
                    </button>
                    <button @click="editCourse(course)" class="btn-small btn-edit" title="编辑">
                      ✏️
                    </button>
                    <button @click="deleteCourseConfirm(course)" class="btn-small btn-delete" title="删除">
                      🗑️
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 创建课程对话框 -->
    <div v-if="showCreateCourse" class="modal-overlay" @click.self="showCreateCourse = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ editingCourse ? '编辑课程' : '创建课程' }}</h3>
          <button @click="showCreateCourse = false" class="btn-close">✕</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>课程名称 <span class="required">*</span></label>
            <input v-model="courseForm.title" type="text" placeholder="例如：微积分基础入门" />
          </div>
          
          <div class="form-group">
            <label>课程描述 <span class="required">*</span></label>
            <textarea v-model="courseForm.description" rows="3" placeholder="简要描述课程内容..."></textarea>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>课程分类 <span class="required">*</span></label>
              <select v-model="courseForm.categoryId">
                <option :value="null">请选择</option>
                <option v-for="cat in categories" :key="cat.id" :value="cat.id">
                  {{ cat.icon }} {{ cat.name }}
                </option>
              </select>
            </div>
            
            <div class="form-group">
              <label>难度等级 <span class="required">*</span></label>
              <select v-model="courseForm.difficulty">
                <option value="beginner">入门</option>
                <option value="intermediate">进阶</option>
                <option value="advanced">高级</option>
              </select>
            </div>
          </div>
          
          <div class="form-group">
            <label>讲师</label>
            <input :value="userInfo.username" type="text" disabled style="background: #f6f8fa; cursor: not-allowed;" />
            <p class="field-tip">当前登录用户将作为课程讲师</p>
          </div>
          
          <div class="form-group">
            <label>课程封面</label>
            <div class="cover-upload">
              <img 
                v-if="courseForm.cover" 
                :src="courseForm.cover" 
                class="cover-preview" 
              />
              <div class="upload-area">
                <input 
                  type="file" 
                  ref="coverInput" 
                  accept="image/*" 
                  @change="handleCoverUpload" 
                  style="display: none;"
                />
                <button @click="$refs.coverInput.click()" class="btn-upload" type="button">
                  {{ courseForm.cover ? '更换封面' : '上传封面' }}
                </button>
                <p class="upload-tip">推荐尺寸：1200×675（16:9）</p>
              </div>
            </div>
          </div>
          
          <div class="form-group">
            <label>状态</label>
            <select v-model="courseForm.status">
              <option value="draft">草稿</option>
              <option value="published">发布</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showCreateCourse = false" class="btn-cancel">取消</button>
          <button @click="saveCourse" class="btn-primary" :disabled="saving">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 章节管理对话框 -->
    <div v-if="showChapterManage" class="modal-overlay" @click.self="showChapterManage = false">
      <div class="modal-content modal-large">
        <div class="modal-header">
          <h3>📚 管理章节和视频 - {{ currentCourse?.title }}</h3>
          <button @click="showChapterManage = false" class="btn-close">✕</button>
        </div>
        <div class="modal-body">
          <!-- 章节列表 -->
          <div class="chapter-list">
            <div v-for="(chapter, index) in chapters" :key="chapter.id" class="chapter-item">
              <div class="chapter-header">
                <h4>第{{ index + 1 }}章：{{ chapter.title }}</h4>
                <div class="chapter-actions">
                  <button @click="showAddVideo(chapter)" class="btn-small btn-primary">
                    ➕ 添加视频
                  </button>
                  <button @click="deleteChapter(chapter)" class="btn-small btn-delete">
                    删除章节
                  </button>
                </div>
              </div>
              
              <!-- 视频列表 -->
              <div v-if="chapter.videos && chapter.videos.length > 0" class="video-list">
                <div v-for="video in chapter.videos" :key="video.id" class="video-item">
                  <span class="video-order">{{ video.orderNum }}</span>
                  <span class="video-title">{{ video.title }}</span>
                  <span class="video-duration">{{ formatDuration(video.duration) }}</span>
                  <button @click="deleteVideo(video)" class="btn-icon btn-delete" title="删除">
                    🗑️
                  </button>
                </div>
              </div>
              <div v-else class="empty-videos">
                暂无视频，点击"添加视频"按钮上传
              </div>
            </div>
          </div>
          
          <!-- 添加章节按钮 -->
          <button @click="showAddChapter = true" class="btn-add-chapter">
            ➕ 添加新章节
          </button>
        </div>
      </div>
    </div>

    <!-- 添加章节对话框 -->
    <div v-if="showAddChapter" class="modal-overlay" @click.self="showAddChapter = false">
      <div class="modal-content modal-small">
        <div class="modal-header">
          <h3>添加章节</h3>
          <button @click="showAddChapter = false" class="btn-close">✕</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>章节标题 <span class="required">*</span></label>
            <input v-model="chapterForm.title" type="text" placeholder="例如：函数与极限" />
          </div>
          <div class="form-group">
            <label>章节描述</label>
            <textarea v-model="chapterForm.description" rows="2" placeholder="简要描述章节内容..."></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showAddChapter = false" class="btn-cancel">取消</button>
          <button @click="saveChapter" class="btn-primary" :disabled="saving">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 添加视频对话框 -->
    <div v-if="showAddVideoDialog" class="modal-overlay" @click.self="showAddVideoDialog = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3>添加视频</h3>
          <button @click="showAddVideoDialog = false" class="btn-close">✕</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>视频标题 <span class="required">*</span></label>
            <input v-model="videoForm.title" type="text" placeholder="例如：1.1 函数的定义" />
          </div>
          
          <div class="form-group">
            <label>视频描述</label>
            <textarea v-model="videoForm.description" rows="2" placeholder="简要描述视频内容..."></textarea>
          </div>
          
          <div class="form-group">
            <label>视频文件 <span class="required">*</span></label>
            <div class="video-upload">
              <input 
                type="file" 
                ref="videoInput" 
                accept="video/*" 
                @change="handleVideoUpload" 
                style="display: none;"
              />
              <button 
                @click="$refs.videoInput.click()" 
                class="btn-upload" 
                type="button"
                :disabled="uploading"
              >
                {{ videoForm.videoUrl ? '更换视频' : '上传视频' }}
              </button>
              <p v-if="videoForm.videoUrl" class="upload-success">✓ 视频已上传</p>
              <p v-if="uploading" class="upload-progress">
                上传中... {{ uploadProgress }}%
              </p>
              <p class="upload-tip">支持 mp4、avi、mov、flv 格式，最大 500MB</p>
            </div>
          </div>
          
          <div class="form-group">
            <label>视频时长（秒） <span class="required">*</span></label>
            <input v-model.number="videoForm.duration" type="number" placeholder="例如：1200" />
            <p class="field-tip">请输入视频的总时长（单位：秒）</p>
          </div>
          
          <div class="form-group">
            <label>观看权限 <span class="required">*</span></label>
            <select v-model="videoForm.accessType">
              <option value="free">免费观看</option>
              <option value="preview">试看（前N分钟免费）</option>
              <option value="course">需购买课程</option>
              <option value="vip">仅限会员</option>
            </select>
          </div>
          
          <div v-if="videoForm.accessType === 'preview'" class="form-group">
            <label>试看时长（秒）</label>
            <input v-model.number="videoForm.previewDuration" type="number" placeholder="例如：300（5分钟）" />
            <p class="field-tip">用户可免费观看的时长</p>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showAddVideoDialog = false" class="btn-cancel">取消</button>
          <button @click="saveVideo" class="btn-primary" :disabled="saving || uploading">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 创建分类对话框 -->
    <div v-if="showCreateCategory" class="modal-overlay" @click.self="showCreateCategory = false">
      <div class="modal-content modal-small">
        <div class="modal-header">
          <h3>创建分类</h3>
          <button @click="showCreateCategory = false" class="btn-close">✕</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>分类名称 <span class="required">*</span></label>
            <input v-model="categoryForm.name" type="text" placeholder="例如：高等数学" />
          </div>
          <div class="form-group">
            <label>图标 <span class="required">*</span></label>
            <input v-model="categoryForm.icon" type="text" placeholder="例如：📐" />
            <p class="field-tip">请输入一个emoji图标</p>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showCreateCategory = false" class="btn-cancel">取消</button>
          <button @click="saveCategory" class="btn-primary" :disabled="saving">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { 
  getCourseCategories,
  getCourseList,
  getCourseDetail,
  createCourse,
  updateCourse,
  deleteCourse,
  createChapter,
  createVideo,
  createCategory,
  uploadVideo,
  uploadCourseCover
} from '../api/learning'

const router = useRouter()
const userStore = useUserStore()

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 如果不是管理员，重定向
if (!userStore.isAdmin) {
  router.replace('/learning')
}

// 数据
const categories = ref([])
const courses = ref([])
const chapters = ref([])
const loading = ref(false)
const saving = ref(false)
const uploading = ref(false)
const uploadProgress = ref(0)

// 筛选
const filterCategory = ref(null)
const filterStatus = ref('')
const searchKeyword = ref('')

// 对话框状态
const showCreateCourse = ref(false)
const showCreateCategory = ref(false)
const showChapterManage = ref(false)
const showAddChapter = ref(false)
const showAddVideoDialog = ref(false)

// 当前操作对象
const editingCourse = ref(null)
const currentCourse = ref(null)
const currentChapter = ref(null)

// 表单数据
const courseForm = ref({
  title: '',
  description: '',
  categoryId: null,
  difficulty: 'beginner',
  cover: '',
  status: 'draft'
})

const chapterForm = ref({
  title: '',
  description: ''
})

const videoForm = ref({
  title: '',
  description: '',
  videoUrl: '',
  duration: 0,
  accessType: 'free',
  previewDuration: 0
})

const categoryForm = ref({
  name: '',
  icon: ''
})

// 计算属性
const filteredCourses = computed(() => {
  let result = courses.value
  
  if (filterCategory.value) {
    result = result.filter(c => c.categoryId === filterCategory.value)
  }
  
  if (filterStatus.value) {
    result = result.filter(c => c.status === filterStatus.value)
  }
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(c => 
      c.title.toLowerCase().includes(keyword) ||
      c.description.toLowerCase().includes(keyword)
    )
  }
  
  return result
})

// 方法
function getAvatarUrl(avatar) {
  if (!avatar) return 'https://via.placeholder.com/32'
  if (avatar.startsWith('http')) return avatar
  return `${import.meta.env.VITE_API_BASE_URL || ''}${avatar}`
}

function getCategoryName(categoryId) {
  const cat = categories.value.find(c => c.id === categoryId)
  return cat ? cat.name : '未分类'
}

function getDifficultyLabel(difficulty) {
  const map = {
    'beginner': '入门',
    'intermediate': '进阶',
    'advanced': '高级'
  }
  return map[difficulty] || difficulty
}

function getStatusLabel(status) {
  const map = {
    'draft': '草稿',
    'published': '已发布'
  }
  return map[status] || status
}

function formatDuration(seconds) {
  if (!seconds) return '00:00'
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

// 加载数据
async function loadCategories() {
  try {
    const res = await getCourseCategories()
    console.log('✅ 分类数据:', res)
    if (res.code === 200) {
      // 与Learning.vue保持一致的数据处理方式
      categories.value = res.data.categories || []
      console.log('📋 加载的分类列表:', categories.value)
    }
  } catch (error) {
    console.error('❌ 加载分类失败:', error)
    alert('加载分类失败：' + error.message)
  }
}

async function loadCourses() {
  loading.value = true
  try {
    const res = await getCourseList({ page: 1, pageSize: 100 })
    if (res.code === 200) {
      courses.value = res.data.list || []
    }
  } catch (error) {
    console.error('加载课程失败:', error)
    alert('加载课程失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 课程操作
function editCourse(course) {
  editingCourse.value = course
  courseForm.value = {
    title: course.title,
    description: course.description,
    categoryId: course.categoryId,
    difficulty: course.difficulty,
    cover: course.cover,
    status: course.status
  }
  showCreateCourse.value = true
}

async function saveCourse() {
  // 验证
  if (!courseForm.value.title || !courseForm.value.description || 
      !courseForm.value.categoryId) {
    alert('请填写所有必填项')
    return
  }
  
  saving.value = true
  try {
    // 构建符合后端要求的数据格式
    const data = {
      categoryId: courseForm.value.categoryId,
      title: courseForm.value.title,
      description: courseForm.value.description,
      cover: courseForm.value.cover || '',  // 封面URL（可为空）
      difficulty: courseForm.value.difficulty,
      instructorId: userInfo.value.id,  // 使用当前登录用户的ID作为讲师ID
      status: courseForm.value.status
    }
    
    console.log('📤 发送数据到后端:', data)
    
    if (editingCourse.value) {
      // 更新课程
      const res = await updateCourse(editingCourse.value.id, data)
      if (res.code === 200) {
        alert('更新成功')
        showCreateCourse.value = false
        editingCourse.value = null
        await loadCourses()
      }
    } else {
      // 创建课程
      const res = await createCourse(data)
      if (res.code === 200) {
        alert('创建成功')
        showCreateCourse.value = false
        await loadCourses()
      }
    }
    
    // 重置表单
    courseForm.value = {
      title: '',
      description: '',
      categoryId: null,
      difficulty: 'beginner',
      cover: '',
      status: 'draft'
    }
  } catch (error) {
    console.error('保存课程失败:', error)
    alert('保存失败：' + error.message)
  } finally {
    saving.value = false
  }
}

async function deleteCourseConfirm(course) {
  if (!confirm(`确定要删除课程"${course.title}"吗？此操作不可恢复！`)) {
    return
  }
  
  try {
    const res = await deleteCourse(course.id)
    if (res.code === 200) {
      alert('删除成功')
      await loadCourses()
    }
  } catch (error) {
    console.error('删除课程失败:', error)
    alert('删除失败：' + error.message)
  }
}

// 章节管理
async function manageChapters(course) {
  currentCourse.value = course
  showChapterManage.value = true
  
  try {
    const res = await getCourseDetail(course.id)
    if (res.code === 200) {
      chapters.value = res.data.chapters || []
    }
  } catch (error) {
    console.error('加载章节失败:', error)
    alert('加载章节失败：' + error.message)
  }
}

async function saveChapter() {
  if (!chapterForm.value.title) {
    alert('请输入章节标题')
    return
  }
  
  saving.value = true
  try {
    const res = await createChapter(currentCourse.value.id, {
      title: chapterForm.value.title,
      description: chapterForm.value.description,
      orderNum: chapters.value.length + 1
    })
    
    if (res.code === 200) {
      alert('添加成功')
      showAddChapter.value = false
      chapterForm.value = { title: '', description: '' }
      // 重新加载章节
      await manageChapters(currentCourse.value)
    }
  } catch (error) {
    console.error('保存章节失败:', error)
    alert('保存失败：' + error.message)
  } finally {
    saving.value = false
  }
}

async function deleteChapter(chapter) {
  if (!confirm(`确定要删除章节"${chapter.title}"吗？`)) {
    return
  }
  
  alert('删除章节功能待后端实现')
}

// 视频管理
function showAddVideo(chapter) {
  currentChapter.value = chapter
  videoForm.value = {
    title: '',
    description: '',
    videoUrl: '',
    duration: 0,
    accessType: 'free',
    previewDuration: 0
  }
  showAddVideoDialog.value = true
}

async function handleVideoUpload(event) {
  const file = event.target.files[0]
  if (!file) return
  
  // 输出文件大小等信息，便于排查
  const fileSizeMB = (file.size / (1024 * 1024)).toFixed(2)
  console.log('🎥 选择视频文件:', {
    name: file.name,
    type: file.type,
    sizeBytes: file.size,
    sizeMB: fileSizeMB
  })
  
  // 验证文件大小（500MB）
  if (file.size > 500 * 1024 * 1024) {
    alert(`视频文件不能超过 500MB（当前约 ${fileSizeMB} MB）`)
    return
  }
  
  uploading.value = true
  uploadProgress.value = 0
  
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const res = await uploadVideo(formData, (progress) => {
      uploadProgress.value = progress
    })
    
    if (res.code === 200) {
      videoForm.value.videoUrl = res.data.videoUrl  // 修复：改为 videoUrl
      alert('视频上传成功')
    }
  } catch (error) {
    console.error('上传视频失败:', error)
    alert('上传失败：' + error.message)
  } finally {
    uploading.value = false
  }
}

async function saveVideo() {
  if (!videoForm.value.title || !videoForm.value.videoUrl || !videoForm.value.duration) {
    alert('请填写所有必填项并上传视频')
    return
  }
  
  // 验证试看时长
  if (videoForm.value.accessType === 'preview' && !videoForm.value.previewDuration) {
    alert('请设置试看时长')
    return
  }
  
  saving.value = true
  try {
    const data = {
      title: videoForm.value.title,
      description: videoForm.value.description,
      videoUrl: videoForm.value.videoUrl,
      duration: videoForm.value.duration,
      accessType: videoForm.value.accessType,
      previewDuration: videoForm.value.accessType === 'preview' ? videoForm.value.previewDuration : 0,
      orderNum: (currentChapter.value.videos?.length || 0) + 1
    }
    
    console.log('📤 保存视频:', data)
    
    const res = await createVideo(currentChapter.value.id, data)
    
    if (res.code === 200) {
      alert('添加成功')
      showAddVideoDialog.value = false
      videoForm.value = { 
        title: '', 
        description: '', 
        videoUrl: '', 
        duration: 0,
        accessType: 'free',
        previewDuration: 0
      }
      // 重新加载章节
      await manageChapters(currentCourse.value)
    }
  } catch (error) {
    console.error('保存视频失败:', error)
    alert('保存失败：' + error.message)
  } finally {
    saving.value = false
  }
}

async function deleteVideo(video) {
  if (!confirm(`确定要删除视频"${video.title}"吗？`)) {
    return
  }
  
  alert('删除视频功能待后端实现')
}

// 封面上传
async function handleCoverUpload(event) {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    alert('封面图片不能超过 5MB')
    return
  }
  
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const res = await uploadCourseCover(formData)
    if (res.code === 200) {
      courseForm.value.cover = res.data.coverUrl  // 修复：改为 coverUrl
      alert('封面上传成功')
    }
  } catch (error) {
    console.error('上传封面失败:', error)
    alert('上传失败：' + error.message)
  }
}

// 分类管理
async function saveCategory() {
  if (!categoryForm.value.name || !categoryForm.value.icon) {
    alert('请填写所有必填项')
    return
  }
  
  saving.value = true
  try {
    const res = await createCategory({
      name: categoryForm.value.name,
      icon: categoryForm.value.icon,
      sortOrder: categories.value.length + 1
    })
    
    if (res.code === 200) {
      alert('创建成功')
      showCreateCategory.value = false
      categoryForm.value = { name: '', icon: '' }
      await loadCategories()
    }
  } catch (error) {
    console.error('创建分类失败:', error)
    alert('创建失败：' + error.message)
  } finally {
    saving.value = false
  }
}

// 初始化
onMounted(() => {
  loadCategories()
  loadCourses()
})
</script>

<style scoped lang="scss">
.learning-manage-page {
  min-height: 100vh;
  background: #f8f9fa;
}

// 顶部导航栏（复用之前的样式）
.top-navbar {
  background: white;
  border-bottom: 1px solid #d0d7de;
  position: sticky;
  top: 0;
  z-index: 100;
  
  .navbar-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 24px;
    height: 64px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .navbar-left {
    .logo-link {
      display: flex;
      align-items: center;
      gap: 8px;
      text-decoration: none;
      color: #667eea;
      
      svg {
        color: #667eea;
      }
      
      .logo {
        font-size: 20px;
        font-weight: 700;
      }
    }
  }
  
  .navbar-center {
    display: flex;
    gap: 8px;
    
    .nav-link {
      padding: 8px 16px;
      color: #57606a;
      text-decoration: none;
      border-radius: 6px;
      transition: all 0.2s;
      
      &:hover, &.active {
        background: #f6f8fa;
        color: #24292f;
      }
    }
  }
  
  .navbar-right {
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .user-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        object-fit: cover;
      }
      
      .username {
        font-size: 14px;
        color: #24292f;
      }
    }
  }
}

// 主内容
.main-content {
  padding: 32px 24px;
}

.content-container {
  max-width: 1400px;
  margin: 0 auto;
}

// 页面标题
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  
  h1 {
    font-size: 32px;
    margin: 0 0 8px 0;
    color: #24292f;
  }
  
  .subtitle {
    font-size: 16px;
    color: #57606a;
    margin: 0;
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
  }
}

// 筛选栏
.filter-bar {
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .filter-left {
    display: flex;
    gap: 12px;
  }
  
  .filter-select {
    padding: 8px 12px;
    border: 1px solid #d0d7de;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
    
    &:focus {
      outline: none;
      border-color: #667eea;
    }
  }
  
  .search-input {
    padding: 8px 12px;
    border: 1px solid #d0d7de;
    border-radius: 6px;
    font-size: 14px;
    width: 260px;
    
    &:focus {
      outline: none;
      border-color: #667eea;
    }
  }
}

// 课程表格
.course-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  
  table {
    width: 100%;
    border-collapse: collapse;
    
    thead {
      background: #f6f8fa;
      
      th {
        padding: 12px 16px;
        text-align: left;
        font-weight: 600;
        color: #24292f;
        font-size: 14px;
      }
    }
    
    tbody {
      tr {
        border-top: 1px solid #d0d7de;
        
        &:hover {
          background: #f6f8fa;
        }
        
        td {
          padding: 16px;
          vertical-align: middle;
          font-size: 14px;
        }
      }
    }
  }
  
  .course-thumb {
    width: 80px;
    height: 45px;
    object-fit: cover;
    border-radius: 4px;
  }
  
  .course-title {
    font-weight: 600;
    color: #24292f;
    margin-bottom: 4px;
  }
  
  .course-desc {
    font-size: 12px;
    color: #57606a;
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .category-badge {
    display: inline-block;
    padding: 4px 8px;
    background: #ddf4ff;
    color: #0969da;
    border-radius: 4px;
    font-size: 12px;
  }
  
  .difficulty-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    
    &.beginner {
      background: #d4edda;
      color: #155724;
    }
    
    &.intermediate {
      background: #fff3cd;
      color: #856404;
    }
    
    &.advanced {
      background: #f8d7da;
      color: #721c24;
    }
  }
  
  .status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    
    &.draft {
      background: #e1e4e8;
      color: #586069;
    }
    
    &.published {
      background: #dcffe4;
      color: #0e6027;
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
  }
}

// 按钮样式
.btn-primary, .btn-secondary, .btn-small, .btn-cancel, .btn-upload, .btn-add-chapter {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  
  &:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  }
}

.btn-secondary {
  background: white;
  border: 1px solid #d0d7de;
  color: #24292f;
  
  &:hover {
    background: #f6f8fa;
  }
}

.btn-cancel {
  background: #e1e4e8;
  color: #586069;
  
  &:hover {
    background: #d1d5da;
  }
}

.btn-small {
  padding: 6px 12px;
  font-size: 12px;
  
  &.btn-manage {
    background: #667eea;
    color: white;
  }
  
  &.btn-edit {
    background: #ffc107;
    color: white;
  }
  
  &.btn-delete {
    background: #dc3545;
    color: white;
  }
}

.btn-icon {
  padding: 4px 8px;
  background: transparent;
  border: none;
  cursor: pointer;
  font-size: 16px;
  
  &.btn-delete:hover {
    background: #f8d7da;
  }
}

.btn-upload {
  background: #667eea;
  color: white;
}

.btn-add-chapter {
  width: 100%;
  margin-top: 16px;
  background: white;
  border: 2px dashed #d0d7de;
  color: #667eea;
  
  &:hover {
    border-color: #667eea;
    background: #f6f8fa;
  }
}

// 加载和空状态
.loading-state, .empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  
  .loading-spinner {
    width: 40px;
    height: 40px;
    margin: 0 auto 16px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  p {
    color: #57606a;
    font-size: 16px;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 模态框
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  
  &.modal-small {
    max-width: 400px;
  }
  
  &.modal-large {
    max-width: 900px;
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #d0d7de;
  
  h3 {
    margin: 0;
    font-size: 20px;
    color: #24292f;
  }
  
  .btn-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #57606a;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    
    &:hover {
      background: #f6f8fa;
    }
  }
}

.modal-body {
  padding: 24px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #d0d7de;
}

// 表单
.form-group {
  margin-bottom: 20px;
  
  label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #24292f;
    font-size: 14px;
    
    .required {
      color: #dc3545;
    }
  }
  
  input, select, textarea {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #d0d7de;
    border-radius: 6px;
    font-size: 14px;
    font-family: inherit;
    
    &:focus {
      outline: none;
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
  }
  
  textarea {
    resize: vertical;
  }
  
  .field-tip {
    margin-top: 4px;
    font-size: 12px;
    color: #57606a;
  }
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

// 封面上传
.cover-upload {
  display: flex;
  gap: 16px;
  align-items: center;
  
  .cover-preview {
    width: 200px;
    height: auto;
    border-radius: 8px;
    border: 1px solid #d0d7de;
  }
  
  .upload-area {
    flex: 1;
  }
  
  .upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #57606a;
  }
}

// 视频上传
.video-upload {
  .upload-success {
    margin-top: 8px;
    color: #28a745;
    font-size: 14px;
  }
  
  .upload-progress {
    margin-top: 8px;
    color: #667eea;
    font-size: 14px;
    font-weight: 600;
  }
  
  .upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #57606a;
  }
}

// 章节管理
.chapter-list {
  .chapter-item {
    margin-bottom: 24px;
    border: 1px solid #d0d7de;
    border-radius: 8px;
    overflow: hidden;
    
    .chapter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      background: #f6f8fa;
      
      h4 {
        margin: 0;
        font-size: 16px;
        color: #24292f;
      }
      
      .chapter-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .video-list {
      padding: 12px 16px;
      
      .video-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 10px;
        background: #f6f8fa;
        border-radius: 6px;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .video-order {
          width: 30px;
          text-align: center;
          font-weight: 600;
          color: #667eea;
        }
        
        .video-title {
          flex: 1;
          font-size: 14px;
          color: #24292f;
        }
        
        .video-duration {
          font-size: 12px;
          color: #57606a;
          min-width: 60px;
          text-align: right;
        }
      }
    }
    
    .empty-videos {
      padding: 24px;
      text-align: center;
      color: #57606a;
      font-size: 14px;
    }
  }
}
</style>

